<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      ref="crud"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.before_pack_add" @click="handleAdd">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" :disabled="ids.length === 0" v-if="permission.before_pack_del" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" size="small" @click="openAndCloseConfig(row)"> {{ row.status === 1 ? '禁用' : '启用' }}</el-button>
        <el-button type="text" size="small" icon="el-icon-view" v-if="permission.before_pack_view" @click="handleView(row)">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.before_pack_edit" @click="handleEdit(row)">编辑 </el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.before_pack_del" @click="rowDel(row)">删除</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
    <!--      详情弹窗 -->
    <!--    <view-plan-config ref="viewConfig" :visible.sync="viewVisible"></view-plan-config>-->
    <!--      编辑新增弹窗 -->
    <!--    <edit-plan-config ref="editConfig" :dialog-type="dialogType" :visible.sync="editOrAddVisible" @closeDialog="handleCloseDialog"></edit-plan-config>-->
    <!--公用模态弹框-->

    <!--    详情-->
    <!--    <view-shipment-plan-config ref="viewConfig" :visible.sync="viewVisible"></view-shipment-plan-config>-->
    <!--    编辑-->
    <view-before-packing-plan-config ref="viewConfig" :visible.sync="viewVisible"></view-before-packing-plan-config>
    <edit-before-packing-plan-config
      ref="editConfig"
      :dialog-type="dialogType"
      :visible.sync="editOrAddVisible"
      @closeDialog="handleCloseDialog"
    ></edit-before-packing-plan-config>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"> </common-modal-template>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getPlainConfigList, openAndCloseConfig, removePlanConfig } from '@/api/quality/palnConfig';
import editBeforePackingPlanConfig from '@/views/quality/refactor/components/editBeforePackingPlanConfig';
import viewBeforePackingPlanConfig from '@/views/quality/refactor/components/viewBeforePackingPlanConfig';
export default {
  name: 'beforePackingPlanConfig',
  components: {
    editBeforePackingPlanConfig,
    viewBeforePackingPlanConfig,
    userTableConfig,
    commonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      dialogType: '',
      editOrAddVisible: false,
      viewVisible: false,
      form: {},
      query: {},
      tableOption: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      selectionList: [],
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 440px)',
        selectionList: [],
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        searchSpan: 5,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        selection: true,
        column: [
          {
            label: '计划名称',
            prop: 'planName',
            searchOrder: 3,
            search: true
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            type: 'search',
            searchOrder: 1,
            hide: true,
            display: true,
            appendClick: () => {
              this.openPartModal();
            }
          },
          {
            label: '适用产品',
            prop: 'partNos'
          },
          {
            label: '更新人',
            prop: 'userName'
          },
          {
            label: '最新时间',
            prop: 'updateTime'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            filterable: true,
            search: true,
            dicData: [
              { label: '禁用', value: 0 },
              { label: '启用', value: 1 }
            ],
            searchOrder: 4
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  beforeRouteEnter(to, from, next) {
    // edit页面过来刷新表格
    if (from.path === '/quality/refactor/editPlanConfig') {
      next((vm) => {
        vm.$nextTick(() => {
          vm.onLoad(vm.page);
        });
      });
    } else {
      next();
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permission.plan_config_del, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await removePlanConfig({ ids: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleAdd() {
      this.dialogType = 'add';
      this.editOrAddVisible = true;
    },
    async handleEdit(row) {
      await this.$refs.editConfig.getDetail(row.id);
      this.dialogType = 'edit';
      this.editOrAddVisible = true;
    },

    async handleView(row) {
      await this.$refs.viewConfig.getDetail(row.id);
      this.viewVisible = true;
    },

    async openAndCloseConfig(row) {
      try {
        await openAndCloseConfig(row.id);
        this.$message.success('操作成功');
        this.onLoad(this.page);
      } catch (e) {}
    },
    handleCloseDialog() {
      this.onLoad(this.page);
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await removePlanConfig({ ids: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    searchChange(params, done) {
      if (params.partNo) {
        params.partNoList = params.partNo.split(',');
      } else {
        delete params.partNoList;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getSelectedRows(rowData) {
      console.log(rowData);
      this.query.partNo = rowData.map((item) => item.partNo).join(',') || '';
      this.query.partNoList = rowData.map((item) => item.partNo);
    },
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '物料编码（双击进行选择）',
        url: '/api/mes-admin/partmaster/query-page-qms-part-master',
        isPage: true,
        selection: false,
        columnDefs: [
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name'
          },
          {
            label: '型号',
            search: true,
            prop: 'partModel'
          }
        ]
      };
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        delete params.partNo;
        const res = await getPlainConfigList(page.currentPage, page.pageSize, Object.assign(params, this.query, { inspectType: 'FQC' }));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records || [];
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
